package vn.nt.healthcare.server.ws.service.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import vn.nt.healthcare.server.ws.domain.Company;
import vn.nt.healthcare.server.ws.model.Customer;
import vn.nt.healthcare.server.ws.repositories.CompanyRepository;
import vn.nt.healthcare.server.ws.service.CustomerService;

@Service("customerService")
@Transactional
public class CustomerServiceImpl implements CustomerService {

	@Autowired
	private CompanyRepository companyRepository;

	@SuppressWarnings("unchecked")
	@Override
	public List<Customer> findAllCustomer(String companyId) {
		// TODO Auto-generated method stub
		Company company = companyRepository.findByCode(companyId);
		if (company != null) {
			Session session = null;
			try {
				session = ServiceHelper.openSession(company);
				StringBuilder sql = new StringBuilder(
						"SELECT DISTINCT c FROM Customer c WHERE 1 = 1");
				Query query = session.createQuery(sql.toString());
				return query.list();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				ServiceHelper.closeSession(session);
			}
		}
		return null;
	}

	@Override
	public Customer findCustomerById(String companyId, int id) {
		// TODO Auto-generated method stub
		Company company = companyRepository.findByCode(companyId);
		if (company != null) {
			Session session = null;
			try {
				session = ServiceHelper.openSession(company);
				Customer customer = (Customer) session.get(Customer.class, id);
				return customer;
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				ServiceHelper.closeSession(session);
			}
		}
		return null;
	}

}
